import { Modal } from '@douyinfe/semi-ui'
import store from '../models/store.ts'
import { Invoice } from '../models/PdfInvoiceResult.ts'
import { useState } from 'react'
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

export default function CopyCodeModal({ visible, setVisible }: { visible: boolean, setVisible: (b: boolean) => void }) {
    const code = generateCode();
    const [copied, setCopied] = useState(false);

    function copy() {
        // 将文本复制到粘贴板
        navigator.clipboard.writeText(code)
        .then(() => {
            toast.success('已复制到粘贴板', {
                position: toast.POSITION.BOTTOM_RIGHT,
                autoClose: 2000,
            })

        })
        .catch(() => {
            toast.error('无法将文本复制到粘贴板', {
                position: toast.POSITION.BOTTOM_RIGHT,
                autoClose: 2000,
            })
        });
    }

    return <>
        <Modal
            header={null}
            visible={visible}
            onOk={copy}
            okText={copied ? '已复制' : '复制'}
            cancelText={'关闭'}
            width={'60vw'}
            height={'80vh'}
            onCancel={() => setVisible(false)}
        >
            <ToastContainer />
            <h3 style={{ textAlign: 'center', fontSize: 24, margin: 40 }}>在电子发票录入的界面，按F12，拷贝以下内容，复制到IE的控制台中并执行</h3>
            <pre style={{ margin: 20, padding: 15, background: '#f7f7f7', height: '60vh', overflow: 'scroll' }}>{code}</pre>

        </Modal>
    </>
}

function generateCode() {
    const invoices = store.pdfSuccessResults.filter(x => x.selected).map(x => x.invoice);
    let code = `
    function findFrame(frame, keyword) {
        // 检查当前 frame 的 URL 是否包含关键字
        if (frame.location.href.indexOf(keyword) >= 0) {
            return frame;
        }

        // 遍历当前 frame 的子 frame
        for (var i = 0; i < frame.frames.length; i++) {
            var childFrame = frame.frames[i];

            // 递归查找子 frame
            var result = findFrame(childFrame, keyword);
            if (result) {
                return result;
            }
        }
        // 如果未找到目标 frame，则返回 null
        return null;
    }
    
    cd(window.top);

    var targetFrame = findFrame(window, 'Invoice_AddAndUse');
    if (!targetFrame) {
        alert('未找到目标Frame，请打开电子发票录入界面');
        return;
    }
    cd(targetFrame);
    var rowIds= [];
    var grid = targetFrame.window.mygrid;
    function renderRow(index, type, code, number, total) {
        var id = rowIds[index];
        grid.cells(id, 1).setValue(type); 
        grid.cells(id, 2).setValue(code);
        grid.cells(id, 3).setValue(number);
        grid.cells(id, 4).setValue(total);
    }

    function addRows(count) {
        if (count <= 5) return;
        for (var i = 0; i < count - 5; i++) {
            targetFrame.window.AddFileGrid();
        }
    }
    addRows(${invoices.length}); // 添加行
    grid.forEachRow(function (id) {
        rowIds.push(id);
    })\r\n`
    for (let i = 0; i < invoices.length; i++) {
        const invoice = invoices[i];
        code += `   renderRow(${i}, '${invoiceType(invoice)}', '${invoice.code}', '${invoice.number}', '${invoice.totalAmount}');\r\n`
    }
    code = `
function runPasteCode() {
    ${code}
}
runPasteCode();
`
    return code;
}


function invoiceType(invoice: Invoice): string {
    if (!invoice.number) return 'ElectronicPlainInvoice'
    if (invoice.code && invoice.number) return 'PlainInvoice';
    return 'ElectronicSpecialInvoice'
}

